package abaco.symbol.operation;

import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JMenuItem;
import javax.swing.JOptionPane;

import abaco.Symbol;
import abaco.gui.Menu;
import abaco.gui.Menuable;
import abaco.gui.Panel;
import abaco.symbol.Operation;
import abaco.symbol.Text;

public class Root extends Operation implements Menuable{
	public static final String INDEX = "operation-root-index";
	public static final String RADICAND = "operation-root-radicand";
	protected Menu menu = new Menu();
	public Root() {
		setSymbolChild(new Text(), INDEX);
		setSymbolChild(new Text(), RADICAND);
	}
	@Override
	public void buildCustonMenu() {
		JMenuItem latex = new JMenuItem("Latex view");
		latex.addActionListener(new ActionListener() {  
            public void actionPerformed(ActionEvent ae) {  
            	JOptionPane.showMessageDialog(null, toLatex());  
            }
        });
		menu.add(latex);
	}
	@Override
	public Menu getMenu() {
		return menu;
	}
	@Override
	public Symbol buildPanel(Panel panel) {
		panel.setLayout(new GridBagLayout());

		// index
		Panel indexPanel = getChildPanel(INDEX, true);
		GridBagConstraints indexConstraints = new GridBagConstraints();
		indexConstraints.gridx = 0;
		indexConstraints.gridy = 0;
		panel.add(indexPanel, indexConstraints);

		// radicand
		Panel radicandPanel = getChildPanel(RADICAND, false);
		GridBagConstraints radicandConstraints = new GridBagConstraints();
		radicandConstraints.gridx = 1;
		radicandConstraints.gridy = 1;
		radicandConstraints.insets = new Insets(-15, 10, 0, 0);
		panel.add(radicandPanel, radicandConstraints);

		return this;
	}

	@Override
	public String toLatex() {
		StringBuilder latex = new StringBuilder();
		latex.append("{\\sqrt");
		String index = toLatex(INDEX);
		if (!index.equals(UNDEFINED_LATEX)) {
			latex.append("[" + index + "]");
		}
		latex.append(toLatex(RADICAND));
		latex.append("}");
		return latex.toString();
	}
}
